export function combinedDisplayWord(word) {
  return addEnterCharForDisplay(word.content +
    (word.pitch ? word.pitch + '-' : '') +
    word.meaning +
    (word.category && word.category !== 'Select' ? ',' + word.category : '') +
    (word.special ? ',特殊' : '')
  );
}

export function combinedDisplayGrammar(grammar) {
  if (grammar.contentList.length === 1 && grammar.contentList[0].content.includes("->")) {
    return `${grammar.category}\n${grammar.contentList[0].content}`;
  }
  if (grammar.contentList.length === 1) {
    return addEnterCharForDisplay(grammar.contentList[0].content);
  }
  return combineMultiLine(grammar);
}

function addEnterCharForDisplay(val) {
  if (val.length < 10) {
    return val;
  }
  return addEnterCharInRightPosition(val);
}

function combineMultiLine(grammar) {
  let result = grammar.category + '\n';
  for (let i = 0; i < grammar.contentList.length; i++) {
    result += grammar.contentList[i].content + '\n';
  }
  return result.substring(0, result.length - 1);
}

function addEnterCharInRightPosition(val) {
  let enterCharPosition = calEnterCharPosition(val);
  if (enterCharPosition == 0) {
    return val;
  }
  return val.substring(0, enterCharPosition) + '\n' + val.substring(enterCharPosition);
}

function calEnterCharPosition(val) {
  let midPosition = val.length / 2;
  let allSymbolPositions = getAllSymbolPositions(val);
  return getMinDistancePosition(midPosition, allSymbolPositions) + 1;
}

function getAllSymbolPositions(val) {
  let symbolPositions = [];
  symbolPositions.push(val.indexOf("-"));
  addAllCommaPositions(val, symbolPositions);
  return symbolPositions;
}

function addAllCommaPositions(val, symbolPositions) {
  if (!val.includes(",")) {
    return;
  }
  while(val.includes(",")) {
    symbolPositions.push(val.indexOf(","));
    val = val.replace(",", "*");
  }
}

function getMinDistancePosition(midPosition, allSymbolPositions) {
  let result = 0;
  let minDistance = Number.MAX_VALUE;
  for (let i = 0; i < allSymbolPositions.length; i++) {
    if (Math.abs(midPosition - allSymbolPositions[i]) < minDistance) {
      minDistance = Math.abs(midPosition - allSymbolPositions[i]);
      result = allSymbolPositions[i];
    }
  }
  return result;
}